<template>
  <div class="upload-excel">
    <div class="btn-upload">
      <el-button :loading="loading" type="primary" @click="handleUpload">
        {{ $t('msg.uploadExcel.upload') }}
      </el-button>
    </div>

    <input
      ref="excelUploadInput"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleChange"
    />
    <!-- https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_Drag_and_Drop_API -->
    <div
      class="drop"
      @drop.stop.prevent="handleDrop"
      @dragover.stop.prevent="handleDragover"
      @dragenter.stop.prevent="handleDragover"
    >
      <i class="el-icon-upload" />
      <span>{{ $t('msg.uploadExcel.drop') }}</span>
    </div>
  </div>
</template>

<script setup>
import XLSX from 'xlsx';
import { ref, defineProps } from 'vue';
import { getHeaderRow, isExcel } from './utils';
import { ElMessage } from 'element-plus';

const props = defineProps({
  // 上传之前的回调
  beforeUpload: Function,
  // 上传成功的回调
  onSuccess: Function
});

const loading = ref(false);
const excelUploadInput = ref(null);

const handleUpload = () => {
  excelUploadInput.value.click();
};

const handleChange = (e) => {
  const files = e.target.files;
  const rawFile = files[0]; // 只上传一个文件
  if (!rawFile) return;
  upload(rawFile);
};

// 拖拽上传
const handleDrop = (e) => {
  // 上传中，不上传该文件
  if (loading.value) return;
  const files = e.dataTransfer.files;
  if (files.length !== 1) {
    ElMessage.error('必须上传一个文件');
    return;
  }
  const rawFile = files[0]; // 只上传一个文件
  if (!isExcel(rawFile)) {
    ElMessage.error('只能上传Excel文件');
    return;
  }
  upload(rawFile);
};
const handleDragover = (e) => {
  e.dataTransfer.dropEffect = 'copy';
};

const upload = (rawFile) => {
  excelUploadInput.value.value = null; // 重置
  // 用户没有指定上传前回调，直接读数据
  if (!props.beforeUpload) {
    readData(rawFile);
    return;
  }
  // 如果用户指定上传前回调，只有返回true，才会执行对应后续操作
  const before = props.beforeUpload(rawFile);
  if (before) {
    readData(rawFile);
  }
};

// 读文件（异步）
const readData = (rawFile) => {
  loading.value = true;
  return new Promise((resolve, reject) => {
    const reader = new FileReader();

    // 读取完成时，执行onload
    reader.onload = (e) => {
      // 1.获取解析后数据
      const data = e.target.result;
      // 2.利用XLSX对数据解析
      const workbook = XLSX.read(data, { type: 'array' });
      // 3.读sheet1数据
      const firstSheetName = workbook.SheetNames[0];
      const workSheet = workbook.Sheets[firstSheetName];
      // 4.解析数据表头
      const header = getHeaderRow(workSheet);
      // 5.解析数据体
      const results = XLSX.utils.sheet_to_json(workSheet);
      // 6.传入解析后数据
      generateData({ results, header });
      // 7.处理loading
      loading.value = false;
      // 8.成功回调
      resolve();
    };

    reader.readAsArrayBuffer(rawFile);
  });
};

// 根据导入内容，生成数据
const generateData = (excelData) => {
  props.onSuccess && props.onSuccess(excelData);
};
</script>

<style lang="scss" scoped>
.upload-excel {
  display: flex;
  justify-content: center;
  margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    line-height: 60px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
</style>
